﻿using leaf.Entity;
using System;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace leaf.Base
{
    /// <summary>
    /// 基础支撑类
    /// 工具方法、提供更新AccessToken、获取微信登录用户信息
    /// </summary>
    public static class BaseSupport
    {
        /// <summary>
        /// 微信接口调用凭据管理
        /// </summary>
        public static void AccessTokenManage()
        {
            Task task = new Task(GetAccessToken);
            task.Start();//要细心 忘记写这个怎么能行
        }

        /// <summary>
        /// 获取微信接口调用凭据 线程
        /// </summary>
        public static void GetAccessToken()
        {
            string uri = Global.GetWXAccessTokenUri();
            //发起get请求
            try
            {
                Global.log.Info("获取微信操作码");
                var rsp = HttpSay.Get<WXBaseInfo>(uri);
                WXBaseInfo wxBaseInfo = new WXBaseInfo()
                {
                    Access_token = rsp.Access_token,
                    Expires_in = rsp.Expires_in,
                };
                Global.SetWXBaseInfo(wxBaseInfo);
                Global.log.Info("获取服务器AccessToken_>" + wxBaseInfo.Access_token);
                Thread.Sleep(7000000);//成功则休眠一个小时五十分钟左右
            }
            catch (Exception ex)
            {
                Global.log.Error("获取服务器AccessToken 失败> null" + ex.Message);
                Thread.Sleep(2000);//失败2秒后继续请求
                GetAccessToken();
            }
        }

        /// <summary>
        /// 获取微信登录ID 和 操作权限代码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static WXUserAccessToken GetWXUserAccessToken(HttpRequestBase request)
        {
            string code = request.Params["code"];//获取微信服务器授权返回的code值
            string state = request.Params["state"];//验证是否来自微信重定向的请求//更具验证state可以确认消息是否来自微信服务器，暂时就不做了

            var uri = Global.GetUserAccessTokenUri(code);
            Global.log.Info("获取用户操作码");
            var rsp = HttpSay.Get<WXUserAccessToken>(uri);
            try
            {
                Global.log.Info("微信返回 操作用户的accessToken:" + rsp.Access_token);
                Global.log.Info("微信返回 openId:" + rsp.Openid);
            }
            catch (Exception ex)
            {
                Global.log.Error(" 获取用户ID 失败 " + ex.Message);
            }
            return rsp;
        }

        /// <summary>
        /// 根据网页授权 获取用户详细信息
        /// </summary>
        /// <param name="request"></param>
        //public static WXUserInfo GetWXUserInfo(string accessToken, string openId)
        //{

        //    var uri = Global.GetWXUserInfoUri(accessToken, openId);
        //    var rsp = HttpSay.Get<WXUserInfo>(uri);
        //    return rsp;
        //}

        /*工具方法--------------------------------------------------------------------------------------*/

        /// <summary>
        /// SHA1 加密
        /// </summary>
        /// <param name="content">加密字符串</param>
        /// <param name="encode">加密编码类型</param>
        /// <returns></returns>
        public static string SHA1(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytes_in = encode.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                string result = BitConverter.ToString(bytes_out);
                result = result.Replace("-", "");
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="configKey">配置对应key</param>
        /// <returns></returns>
        public static string GetConfig(string configKey)
        {
            var res = ConfigurationManager.AppSettings[configKey];
            return res;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string GetStrForPath(string path)
        {
            String res = "";
            StreamReader sRead = new StreamReader(path, Encoding.Default);
            String line;
            while ((line = sRead.ReadLine()) != null)
            {
                res += line;
            }
            return res;
        }

        /// <summary>
        /// urlEncode 工具方法
        /// </summary>
        /// <param name="uriStr">输入uri</param>
        /// <returns></returns>
        public static string UrlEncode(string uriStr)
        {
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(uriStr);
            StringBuilder build = new StringBuilder();
            for (int i = 0; i < byStr.Length; i++)
            {
                build.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return build.ToString();
        }
    }
}